package number_25;

public class Solution {
    //递归;
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        int index = 1;
        ListNode tmp = head;
        while (index++ < k && tmp.next != null) {
            tmp = tmp.next;
        }
        if (index <= k) {
            return head;
        }
        ListNode curr = tmp.next;
        tmp.next = null;
        tmp = reverseNode(head);
        head.next = reverseKGroup(curr, k);

        return tmp;

    }

    private ListNode reverseNode(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = prev;
            prev = head;
            head = tmp;
        }
        return prev;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    //迭代;
    public ListNode reverseKGroup1(ListNode head, int k) {
         ListNode dummy = new ListNode(-1);
         dummy.next = head;

         ListNode pre = dummy, end = dummy;
         while (end.next != null) {
             for (int i = 0; i < k && end != null; i++) {
                 end = end.next;
             }
             if (end == null) {
                 break;
             }
             ListNode start = pre.next;
             ListNode next = end.next;
             end.next = null;
             pre.next = reverseNode(start);
             start.next = next;

             pre = start;
             end = pre;
         }
         return dummy.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;

        new Solution().reverseKGroup(head, 3);
    }
}
